<?php

namespace Biz\model\activity;

use Biz\model\activity\CouponConfig as mCouponConfig;
use Doraemon\pockets\datebase\BaseDbModel;
use Doraemon\tools\HhzClient;

class CouponRecord extends BaseDbModel
{
    const _CONFIG_FILE_ = 'db_shop';

    const _CONFIG_SELECT_ = 'db_activity';

    const _DATABASE_ = 'shop_activity';

    const _TABLE_NAME = 'coupon_record';


    //状态码
    const  COUPON_STATUS_UNUSED = 1;//未使用
    const COUPON_STATUS_USED = 2;//已使用
    const COUPON_STATUS_EXPIRED = 3;//过期

    //状态描述
    public static $statusDesc = [
        self::COUPON_STATUS_UNUSED => '未使用',
        self::COUPON_STATUS_USED => '已使用',
        self::COUPON_STATUS_EXPIRED => '已过期'
    ];


    //优惠券领取方式
    const RECEIVE_WAY_SELF = 1;//自己领取
    const RECEIVE_WAY_ADMIN = 2;//管理员发放

    public static function insertCoupon($uid, $couponId, $data)
    {
        unset($data['include_goods_ids']);
        unset($data['exclude_goods_ids']);
        unset($data['include_brand_ids']);

        self::insert(array_merge([
            'uid' => $uid,
            'coupon_id' => $couponId,
            'addtime' => date('Y-m-d H:i:s')
        ], $data));
    }

    public static function getUserHasCouponSum($uid, $couponId)
    {
        return self::count(['uid' => $uid, 'coupon_id' => $couponId]);
    }

    public static function getUnUsed($uid, $couponId)
    {
        return self::select('*', [
            'uid' => $uid,
            'coupon_id' => $couponId,
            'status' => self::COUPON_STATUS_UNUSED
        ]);
    }

    public static function getUserCoupons($uid, array $couponIds)
    {
        return self::select("*", [
            'uid' => $uid,
            'coupon_id' => $couponIds,
            'status' => self::COUPON_STATUS_UNUSED
        ]);
    }

    public static function getUserCouponSum($uid)
    {
        $couponIds = self::select('coupon_id', ['uid' => $uid, 'status' => self::COUPON_STATUS_UNUSED, 'stop_time[>]' => date('Y-m-d H:i:s')]);
        if (!empty($couponIds)) {
            $configWhere['coupon_id'] = $couponIds;
            $configWhere['channel'] = [
                mCouponConfig::COUPON_CHANNEL_APP,
                mCouponConfig::COUPON_CHANNEL_OUT_APP,
            ];
            if (HhzClient::getClientType() && HhzClient::getClientType() == HhzClient::APPTYPE_PARAGRAPH_MINIPROGRAM) {
                $configWhere['channel'] = mCouponConfig::COUPON_CHANNEL_THE_PARAGRAPH;
            }
            return mCouponConfig::getCount($configWhere);
        } else {
            return 0;
        }
    }
}